package com.imooc.springcloud;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

/**
 * @author L
 */
@RestController
public class Controller {

    @Autowired
    private JwtService jwtService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/login")
    public AuthResponse login(@RequestParam("username") String username, @RequestParam("password") String password) {
        Account account = Account.builder()
                .username(username)
                .build();
        String token = jwtService.token(account);
        account.setToken(token);
        account.setRefreshToken(UUID.randomUUID().toString());
        redisTemplate.opsForValue().set(account.getRefreshToken(), account);
        return AuthResponse.builder()
                .account(account)
                .code(ResponseCode.SUCCESS)
                .build();
    }

    @PostMapping("/refresh")
    public AuthResponse refresh(@RequestParam("refreshToken") String refreshToken) {
        Account account = (Account) redisTemplate.opsForValue().get(refreshToken);
        if (account == null) {
            return AuthResponse.builder().code(ResponseCode.USER_NOT_FOUND).build();
        }
        account.setToken(jwtService.token(account));
        account.setRefreshToken(UUID.randomUUID().toString());
        redisTemplate.delete(refreshToken);
        redisTemplate.opsForValue().set(account.getRefreshToken(), account);
        return AuthResponse.builder()
                .account(account)
                .code(ResponseCode.SUCCESS)
                .build();
    }

    @GetMapping("/verify")
    public AuthResponse verify(@RequestParam String token, @RequestParam String username) {
        boolean result = jwtService.verify(token, username);
        return AuthResponse.builder()
                .code(result ? ResponseCode.SUCCESS : ResponseCode.USER_NOT_FOUND)
                .build();
    }
}
